package com.it.bigdata.zookeeper;

import com.it.bigdata.mail.MyMail;
import org.apache.zookeeper.*;
import org.dom4j.Document;
import org.dom4j.io.SAXReader;
import org.dom4j.tree.DefaultElement;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ZookeeperWatch {
    private static ZooKeeper zk;


    //初始化zk中数据的方法
    public static void zkInit()  {
        String ip= null;
        try {
            ip = InetAddress.getLocalHost().getHostName();
            String quram=getQuram();
            zk=new ZooKeeper(quram, 3000, new Watcher() {
                @Override
                public void process(WatchedEvent event) {
                }
            });
            //首先连接的创建节点
            zk.create("/node11/"+ip,ip.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }



    //解析xml获取zk其中的地址
    public static String getQuram() throws Exception{
        //获取dom4j的xml解析器
        SAXReader saxReader = new SAXReader();
        //以流加载配置文件
        Document read = saxReader.read(ZookeeperWatch.class.getClassLoader().getResourceAsStream("core.xml"));
        //获取指定标签下的所有节点
        List<DefaultElement> list = read.selectNodes("/configs/conf/name");
        for (DefaultElement defaultElement:list){
            if (defaultElement.getText().equals("zk.quorum")) {
                String text = defaultElement.getParent().elementText("value");
                return text;
            }
        }
        return null;
    }
}
